package cn.wei.youvie.controller;

import cn.wei.youvie.common.annotation.AuthCheck;
import cn.wei.youvie.common.constant.UserConstant;
import cn.wei.youvie.common.exception.BusinessException;
import cn.wei.youvie.common.exception.ThrowUtils;
import cn.wei.youvie.common.servlet.BaseResponse;
import cn.wei.youvie.common.servlet.DeleteRequest;
import cn.wei.youvie.common.servlet.ErrorCode;
import cn.wei.youvie.common.servlet.ResultUtils;
import cn.wei.youvie.domain.dto.chapter.ChapterAddRequest;
import cn.wei.youvie.domain.dto.chapter.ChapterEditRequest;
import cn.wei.youvie.domain.dto.chapter.ChapterQueryRequest;
import cn.wei.youvie.domain.dto.chapter.ChapterUpdateRequest;
import cn.wei.youvie.domain.entity.Chapter;
import cn.wei.youvie.domain.entity.User;
import cn.wei.youvie.domain.vo.ChapterVO;
import cn.wei.youvie.service.ChapterService;
import cn.wei.youvie.service.UserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/chapter")
@Slf4j
public class ChapterController {


    @Resource
    private ChapterService chapterService;

    @Resource
    private UserService userService;

    /**
     * 新建章节
     */
    @PostMapping("/add")
    public BaseResponse<Integer> addChapter(@RequestBody ChapterAddRequest chaptersAddRequest, HttpServletRequest request) {
        Integer chapterId = chapterService.add(chaptersAddRequest, request);
        return ResultUtils.success(chapterId);
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChapter(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        boolean removed = chapterService.deleteChapter(deleteRequest, request);
        return ResultUtils.success(removed);
    }

    /**
     * 更新（仅管理员）
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateChapter(@RequestBody ChapterUpdateRequest chaptersUpdateRequest) {
        boolean updated = chapterService.updateChapter(chaptersUpdateRequest);
        return ResultUtils.success(updated);
    }

    /**
     * 根据 id 获取
     */
    @GetMapping("/get/vo")
    public BaseResponse<ChapterVO> getChapterVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chapter chapter = chapterService.getById(id);
        if (chapter == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chapterService.getChapterVO(chapter, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Chapter>> listChapterByPage(@RequestBody ChapterQueryRequest chaptersQueryRequest) {
        long current = chaptersQueryRequest.getCurrent();
        long size = chaptersQueryRequest.getPageSize();
        Page<Chapter> chaptersPage = chapterService.page(new Page<>(current, size),
                chapterService.getQueryWrapper(chaptersQueryRequest));
        return ResultUtils.success(chaptersPage);
    }

    /**
     * 分页获取列表（封装类）
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ChapterVO>> listChapterVOByPage(@RequestBody ChapterQueryRequest chaptersQueryRequest,
                                                       HttpServletRequest request) {
        long current = chaptersQueryRequest.getCurrent();
        long size = chaptersQueryRequest.getPageSize();
        Page<Chapter> chaptersPage = chapterService.page(new Page<>(current, size),
                chapterService.getQueryWrapper(chaptersQueryRequest));
        return ResultUtils.success(chapterService.getChapterVOPage(chaptersPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ChapterVO>> listMyChapterVOByPage(@RequestBody ChapterQueryRequest chaptersQueryRequest,
                                                         HttpServletRequest request) {
        if (chaptersQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = chaptersQueryRequest.getCurrent();
        long size = chaptersQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chapter> chapterPage = chapterService.page(new Page<>(current, size),
                chapterService.getQueryWrapper(chaptersQueryRequest));
        return ResultUtils.success(chapterService.getChapterVOPage(chapterPage, request));
    }

    /**
     * 分页搜索（从 ES 查询，封装类）
     */
    @PostMapping("/search/page/vo")
    public BaseResponse<Page<ChapterVO>> searchChapterVOByPage(@RequestBody ChapterQueryRequest chaptersQueryRequest,
                                                         HttpServletRequest request) {
        return null;
    }

    /**
     * 编辑（用户）
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChapter(@RequestBody ChapterEditRequest chaptersEditRequest, HttpServletRequest request) {
        if (chaptersEditRequest == null || chaptersEditRequest.getChapterId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chapter chapter = new Chapter();
        BeanUtils.copyProperties(chaptersEditRequest, chapter);

        User loginUser = userService.getLoginUser(request);
        long id = chaptersEditRequest.getChapterId();
        // 判断是否存在
        Chapter oldChapter = chapterService.getById(id);
        ThrowUtils.throwIf(oldChapter == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chapterService.updateById(chapter);
        return ResultUtils.success(result);
    }

    @PostMapping("/getContentByChapterId")
    public BaseResponse<ChapterVO> getContentsByChapterId(@RequestBody ChapterQueryRequest chapterQueryRequest, HttpServletRequest request) {
        if (chapterQueryRequest == null || chapterQueryRequest.getChapterId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(chapterService.getContentsByChapterId(chapterQueryRequest, request));
    }

}
